package org.ilead.iserve.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.ilead.iserve.constants.LopConstants;
import org.ilead.iserve.model.News;
import org.ilead.iserve.model.User;
import org.ilead.iserve.model.base.PageView;
import org.ilead.iserve.service.INewsPageService;
import org.ilead.iserve.service.INewsService;
import org.ilead.iserve.web.base.BaseActionSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;

public class NewsAction extends BaseActionSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1425448000382583760L;

	private static final Logger log = LoggerFactory.getLogger(NewsAction.class);
	private Integer id = new Integer(0);// 用于修改删除时传参数
	private News news = new News();// 用于增改
	private List<News> newsList = new ArrayList<News>();// 用于查询
	private INewsService newsService = null;
	private Map newsCategoryMap = new HashMap();

	@Autowired
	private INewsPageService newsPageService;

	private static final int BUFFER_SIZE = 16 * 1024;

	private File doc;
	private String contentType;
	private String fileName;
	private String imageFileName;

	public NewsAction() {
		newsCategoryMap.put(LopConstants.NEWS_TYPE_SHORTMESSAGE, "公告");
		newsCategoryMap.put(LopConstants.NEWS_TYPE_LONGMESSAGE, "新闻");
	}

	public String addNews() throws Exception {
		ActionContext context = ActionContext.getContext();
		User loginUser = (User) context.getSession().get("LOGINUSER");

		if (loginUser == null)
			return ERROR;

		if (fileName != null && fileName.equals("")) {
			if (!uploadFile().equals(SUCCESS)) {
				this.addFieldError("doc", "上传文件失败");
				return INPUT;
			}
		}

		try {
			news.setOperator(loginUser.getUserName());
			news.setImage(imageFileName);
			news.setGmtCreate(new Timestamp(System.currentTimeMillis()));
			news.setGmtModify(new Timestamp(System.currentTimeMillis()));
			System.out.println(news.getContent());

			newsService.addNews(news);
		} catch (Exception e) {
			log.error("保存文章错误", e);
			return ERROR;
		}
		return SUCCESS;
	}

	public String listNews() throws Exception {
		/**
		 * 下面3句固定
		 */
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx
				.get(ServletActionContext.HTTP_REQUEST);
		int maxResult = 10;
		/**
		 * 修改Bean和service即可
		 */
		LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
		orderby.put("gmtModify", "desc");

		PageView<News> pageView = new PageView<News>(maxResult, getPage());
		pageView.setQueryResult(newsPageService.getScrollData(
				pageView.getFirstResult(), maxResult, orderby));

		/**
		 * request.setAttribute("pageView", pageView)中key尽量为pageView，不然需要修改代码
		 */
		request.setAttribute("pageView", pageView);
		return SUCCESS;
	}

	public String beforeAddNews() throws Exception {
		news = new News();
		return SUCCESS;
	}

	public String editNews() throws Exception {
		try {
			news = newsService.findById(id);
		} catch (Exception e) {
			log.error("修改文章错误", e);
			return ERROR;
		}
		return SUCCESS;
	}

	public String updateNews() throws Exception {

		ActionContext context = ActionContext.getContext();
		User loginUser = (User) context.getSession().get("LOGINUSER");

		if (id == null || id <= 0) {
			return ERROR;
		}

		if (loginUser == null)
			return ERROR;
		
		if (fileName != null && !fileName.equals("")) {
			if (!uploadFile().equals(SUCCESS)) {
				this.addFieldError("doc", "上传文件失败");
				return INPUT;
			}
		}

		try {

			News updateNews = newsService.findById(id);

			if (updateNews == null) {
				return ERROR;
			}

			updateNews.setCategoryId(news.getCategoryId());
			updateNews.setAuthor(news.getAuthor());
			updateNews.setContent(news.getContent());
			updateNews.setImage(imageFileName);
			updateNews.setKeyWords(news.getKeyWords());
			updateNews.setOutline(news.getOutline());
			updateNews.setStatus(news.getStatus());
			updateNews.setOperator(loginUser.getUserName());
			updateNews.setTitle(news.getTitle());
			updateNews.setGmtModify(new Timestamp(System.currentTimeMillis()));
			System.out.println(news.getContent());

			newsService.updateNews(updateNews);

		} catch (Exception e) {
			log.error("更新文章错误", e);
			return ERROR;
		}
		return SUCCESS;
	}

	public String delNews() throws Exception {
		try {
			newsService.delNews(id);
		} catch (Exception e) {
			log.error("删除文章错误", e);
			return ERROR;
		}
		return SUCCESS;
	}

	private String uploadFile() {

		imageFileName = new Date().getTime() + getExtention(fileName);
		File imageFile = new File(ServletActionContext.getServletContext()
				.getRealPath(LopConstants.UPLOAD_IMAGE_PATH)
				+ File.separatorChar + imageFileName);
		copy(doc, imageFile);
		return SUCCESS;
	}

	private static void copy(File src, File dst) {
		try {
			InputStream in = null;
			OutputStream out = null;
			try {
				in = new BufferedInputStream(new FileInputStream(src),
						BUFFER_SIZE);
				out = new BufferedOutputStream(new FileOutputStream(dst),
						BUFFER_SIZE);
				byte[] buffer = new byte[BUFFER_SIZE];
				while (in.read(buffer) > 0) {
					out.write(buffer);
				}
			} finally {
				if (null != in) {
					in.close();
				}
				if (null != out) {
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static String getExtention(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos);
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public News getNews() {
		return news;
	}

	public void setNews(News news) {
		this.news = news;
	}

	public List<News> getNewsList() {
		return newsList;
	}

	public void setNewsList(List<News> newsList) {
		this.newsList = newsList;
	}

	public Map getNewsCategoryMap() {
		return newsCategoryMap;
	}

	public void setNewsCategoryMap(Map newsCategoryMap) {
		this.newsCategoryMap = newsCategoryMap;
	}

	public void setNewsService(INewsService newsService) {
		this.newsService = newsService;
	}

	public File getDoc() {
		return doc;
	}

	public void setDoc(File doc) {
		this.doc = doc;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public void setDocFileName(String fileName) {
		this.fileName = fileName;
	}

	public void setDocContentType(String contentType) {
		this.contentType = contentType;
	}

	public String getImageFileName() {
		return imageFileName;
	}

	public void setImageFileName(String imageFileName) {
		this.imageFileName = imageFileName;
	}

}
